package mrms.api.service;

import lombok.AllArgsConstructor;
import mrms.api.entity.MeetingEntity;
import mrms.api.entity.MeetingmemberEntity;
import mrms.api.entity.RoomEntity;
import mrms.api.entity.UserEntity;
import mrms.api.repository.MeetingMemberRepository;
import mrms.api.repository.MeetingRepository;
import mrms.api.repository.RoomRepository;
import mrms.api.repository.UserRepository;
import mrms.api.web.utils.MeetingAdjust;
import mrms.api.web.utils.MeetingState;
import mrms.api.web.utils.MessageType;
import mrms.api.web.utils.TimeUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 * @author lenchu
 * @date 2019/02/24
 */
@Service
@AllArgsConstructor
public class MeetingService {
    private final MeetingRepository meetingRepository;
    private final RoomRepository roomRepository;
    private final MeetingMemberRepository meetingMemberRepository;
    private final UserRepository userRepository;
    private final MessageService messageService;
    @Transactional
    public MeetingEntity saveMeetingAndAutoRoom(MeetingEntity meetingEntity, RoomEntity roomEntity) {
        RoomEntity savedRoom = roomRepository.save(roomEntity);
        meetingEntity.setRoom(savedRoom.getId());
        return meetingRepository.save(meetingEntity);
    }


    @Scheduled(cron = "0 */1 * * * ?")
    public void autoMeeting(){
        Long day= TimeUtils.getOneDayZeroPointTimestamps(new Date().getTime())/1000+60*60*24;
        Long datafter=day+60*60*24;
        System.out.println(day+"   "+datafter);
        List<MeetingEntity> meetingEntities=meetingRepository.findByStarttimeBetweenAndAdjustOrderByStarttime(day,datafter,0);
        System.out.println(meetingEntities.size());
        meetingEntities.stream()
                .forEach(meetingEntity -> {
                    List<RoomEntity> roomEntities;
                    RoomEntity roomEntity=roomRepository.findRoomEntityById(meetingEntity.getRoom());
                    if (roomEntity.getFloor()==0) roomEntities=roomRepository.findRoomEntitiesByAirconditionerGreaterThanEqualAndMediaGreaterThanEqualAndSizeGreaterThanEqualAndTypeOrderBySizeAsc(roomEntity.getAirconditioner(),roomEntity.getMedia(),meetingEntity.getExpectsize(),0);
                    else roomEntities=roomRepository.findRoomEntitiesByAirconditionerGreaterThanEqualAndMediaGreaterThanEqualAndFloorAndSizeGreaterThanEqualAndTypeOrderBySizeAsc(roomEntity.getAirconditioner(),roomEntity.getMedia(),roomEntity.getFloor(),meetingEntity.getExpectsize(),0);
                    for (int i=0;i<roomEntities.size();i++){
                        RoomEntity roomEntity1=roomEntities.get(i);
                        List<MeetingEntity> notimemeetings=meetingRepository.findByStarttimeBetweenAndEndtimeBetweenAndRoom(meetingEntity.getStarttime()-60*15,meetingEntity.getEndtime()+900,meetingEntity.getStarttime()-900,meetingEntity.getEndtime()+900,roomEntity1.getId());
                        List<MeetingEntity> notimemeetings2=meetingRepository.findByStarttimeLessThanEqualAndEndtimeGreaterThanEqualAndRoom(meetingEntity.getStarttime(),meetingEntity.getEndtime(),roomEntity1.getId());
                        if (notimemeetings.size()>0||notimemeetings2.size()>0){
                            roomEntities.remove(roomEntity1);
                        }
                    }
                    if (roomEntities.size()==0){
                        meetingEntity.setState(MeetingState.CHECK_REJECT);
                        meetingEntity.setAdjust(MeetingAdjust.NEVER);
                        meetingRepository.save(meetingEntity);
                        messageService.newMessage(MessageType.MeetingCheck,meetingEntity.getId(),meetingEntity.getSponsor());
                    }
                    else {
                        double max=0;
                        RoomEntity suitableroom=roomEntities.get(0);
                        for (int i=0;i<roomEntities.size();i++){
                            double score;
                            RoomEntity roomEntityx =roomEntities.get(i);
                            List<MeetingEntity> passedmeetings=meetingRepository.findByRoomOrderByEndtimeDesc(meetingEntity.getRoom());
                            if (passedmeetings.size()==0){
                                score=0.5*(roomEntityx.getSize()/meetingEntity.getExpectsize());
                            }
                            else score= (3600/(meetingEntity.getStarttime().doubleValue()-passedmeetings.get(0).getEndtime().doubleValue()))+0.5*(roomEntityx.getSize()/meetingEntity.getExpectsize());
                            if (score>max){
                                max=score;
                                suitableroom=roomEntityx;
                            }
                        }
                        meetingEntity.setRoom(suitableroom.getId());
                        meetingEntity.setAdjust(1);
                        meetingEntity.setState(0);
                        meetingRepository.save(meetingEntity);
                        send_email();//预约成功
                    }
                });

    }
    public void send_email(){
        //TODO
    }

    public List<UserEntity> getAllMembersByMeetingId(Integer mid) {
        List<UserEntity> result = new LinkedList<>();
        Optional<MeetingEntity> optionalMeetingEntity = meetingRepository.findById(mid);
        if (optionalMeetingEntity.isPresent()) {
            MeetingEntity meetingEntity = optionalMeetingEntity.get();
            result.add(userRepository.findById(meetingEntity.getSponsor()).get());
            List<MeetingmemberEntity> meetingmemberEntities = meetingMemberRepository.findAllByMid(mid);
            meetingmemberEntities.stream().forEach(meetingmemberEntity -> {
                result.add(userRepository.findById(meetingmemberEntity.getUid()).get());
            });
        }
        return result;
    }
}
